package com.feng.chat.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.feng.chat.dto.EmoticonListDTO;
import com.feng.chat.dto.Result;
import com.feng.chat.dto.SystemEmoticonListDTO;
import com.feng.chat.entity.*;
import com.feng.chat.mapper.*;
import com.feng.chat.service.IEmoticonService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.feng.chat.vo.CollectEmoticonVO;
import com.feng.chat.vo.SysEmoticonVO;
import com.sun.deploy.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * <p>
 * 表情包 服务实现类
 * </p>
 *
 * @author dyf
 * @since 2022-05-31
 */
@Service
public class EmoticonServiceImpl extends ServiceImpl<EmoticonMapper, Emoticon> implements IEmoticonService {
    @Autowired
    private EmoticonItemMapper emoticonItemMapper;

    @Autowired
    private EmoticonMapper emoticonMapper;

    @Autowired
    private UsersEmoticonMapper usersEmoticonMapper;

    @Autowired
    private TalkRecordsMapper talkRecordsMapper;

    @Autowired
    private TalkRecordsFileMapper talkRecordsFileMapper;

    /**
     * 获取表情包列表
     *
     * @param uid
     * @return
     */
    @Override
    public Result emoticonList(Integer uid) {
        EmoticonListDTO emoticonListDTO = new EmoticonListDTO();

        //收藏表情包列表
        QueryWrapper<EmoticonItem> emoticonItemQueryWrapper = new QueryWrapper<>();
        emoticonItemQueryWrapper.eq("user_id", uid);
        List<EmoticonItem> emoticonItems = emoticonItemMapper.selectList(emoticonItemQueryWrapper);
        List<CollectEmoticonVO> collectEmoticonVOS = new ArrayList<>();
        collectEmoticonVOS = emoticonItems.stream().map(item -> {
            CollectEmoticonVO collectEmoticonVO = new CollectEmoticonVO();
            collectEmoticonVO.setMedia_id(item.getId());
            collectEmoticonVO.setSrc(item.getUrl());
            return collectEmoticonVO;
        }).collect(Collectors.toList());

        emoticonListDTO.setCollect_emoticon(collectEmoticonVOS);

        // 系统表情包列表
        QueryWrapper<UsersEmoticon> usersEmoticonQueryWrapper = new QueryWrapper<>();
        usersEmoticonQueryWrapper.eq("user_id", uid);
        UsersEmoticon usersEmoticon = usersEmoticonMapper.selectOne(usersEmoticonQueryWrapper);
        if (usersEmoticon != null) {
            String emoticonIds = usersEmoticon.getEmoticonIds();

            String[] split = emoticonIds.split(",");

           /* int[] ids = Arrays.stream(emoticonIds.split(",")).mapToInt(s -> Integer.parseInt(s)).toArray();
            List<Integer> eids = Arrays.stream(ids).boxed().collect(Collectors.toList());*/

            QueryWrapper<Emoticon> emoticonQueryWrapper = new QueryWrapper<>();
            emoticonQueryWrapper.in("id", split).eq("status", 0);
            List<Emoticon> emoticonList = list(emoticonQueryWrapper);

            List<SysEmoticonVO> sysEmoticonVOS = new ArrayList<>();
            sysEmoticonVOS = emoticonList.stream().map(item -> {
                SysEmoticonVO sysEmoticonVO = new SysEmoticonVO();
                sysEmoticonVO.setEmoticon_id(item.getId());
                sysEmoticonVO.setUrl(item.getIcon());
                sysEmoticonVO.setName(item.getName());

                QueryWrapper<EmoticonItem> itemQueryWrapper = new QueryWrapper<>();
                itemQueryWrapper.eq("emoticon_id",item.getId()).orderByDesc("updated_at");

                List<EmoticonItem> emoticonItems1 = emoticonItemMapper.selectList(itemQueryWrapper);

                List<CollectEmoticonVO> collectEmoticonVOS1 = new ArrayList<>();
                collectEmoticonVOS1=emoticonItems1.stream().map(eItem -> {
                    CollectEmoticonVO collectEmoticonVO = new CollectEmoticonVO();
                    collectEmoticonVO.setMedia_id(eItem.getId());
                    collectEmoticonVO.setSrc(eItem.getUrl());
                    return collectEmoticonVO;
                }).collect(Collectors.toList());
                sysEmoticonVO.setList(collectEmoticonVOS1);

                return sysEmoticonVO;
            }).collect(Collectors.toList());
            emoticonListDTO.setSys_emoticon(sysEmoticonVOS);
        }

        return Result.success(emoticonListDTO);
    }


    /**
     * 收藏表情包
     * @param uid
     * @param record_id
     * @return
     */
    @Override
    public Result messageCollect(Integer uid, Integer record_id) {
        TalkRecords talkRecords = talkRecordsMapper.selectById(record_id);
        if (talkRecords.getMsgType()==2){
            QueryWrapper<TalkRecordsFile> talkRecordsFileQueryWrapper = new QueryWrapper<>();
            talkRecordsFileQueryWrapper.eq("record_id",record_id);
            TalkRecordsFile talkRecordsFile = talkRecordsFileMapper.selectOne(talkRecordsFileQueryWrapper);

            QueryWrapper<EmoticonItem> emoticonItemQueryWrapper = new QueryWrapper<>();
            emoticonItemQueryWrapper.eq("url",talkRecordsFile.getUrl()).eq("user_id",uid);
            EmoticonItem emoticonItem = emoticonItemMapper.selectOne(emoticonItemQueryWrapper);
            if (emoticonItem!=null){
                return Result.fail("此表情您已经收藏过哦！");
            }
            EmoticonItem emoticonItem1 = new EmoticonItem();
            emoticonItem1.setFileSize(talkRecordsFile.getSize());
            emoticonItem1.setFileSuffix(talkRecordsFile.getSuffix());
            emoticonItem1.setRepresent(talkRecordsFile.getOriginalName());
            emoticonItem1.setUrl(talkRecordsFile.getUrl());
            emoticonItem1.setUserId(uid);
            int insert = emoticonItemMapper.insert(emoticonItem1);
            return Result.success();
        }
        return Result.fail();
    }

    /**
     * 自定义表情包
     * @param uid
     * @param emoticon
     * @return
     */
    @Override
    public Result customizeCreate(Integer uid, MultipartFile emoticon) {
        EmoticonItem emoticonItem = new EmoticonItem();
        String path="E:\\Desktop\\案例\\javaweb案例\\MyChat\\resource\\emoticon\\";
        String oldFileName = emoticon.getOriginalFilename();
        String suffix = oldFileName.substring(oldFileName.lastIndexOf(".") + 1);
        long size = emoticon.getSize();
        String newFileName = UUID.randomUUID().toString().replaceAll("-", "");
        newFileName=newFileName+"."+suffix;
        String url="http://localhost:8081/emoticon/"+newFileName;
        path=path+newFileName;
        File file = new File(path);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        try {
            emoticon.transferTo(file);
        } catch (IOException e) {
            e.printStackTrace();
        }

        emoticonItem.setUserId(uid);
        emoticonItem.setUrl(url);
        emoticonItem.setRepresent("图片表情");
        emoticonItem.setFileSuffix(suffix);
        emoticonItem.setFileSize(size);
        emoticonItemMapper.insert(emoticonItem);

        CollectEmoticonVO collectEmoticonVO = new CollectEmoticonVO();
        collectEmoticonVO.setMedia_id(emoticonItem.getId());
        collectEmoticonVO.setSrc(emoticonItem.getUrl());

        return Result.success(collectEmoticonVO);
    }

    /**
     * 获取系统表情包列表
     * @param uid
     * @return
     */
    @Override
    public Result systemList(Integer uid) {
        List<Emoticon> emoticons = emoticonMapper.selectList(null);
        List<SystemEmoticonListDTO> systemEmoticonListDTOS = new ArrayList<>();

        QueryWrapper<UsersEmoticon> usersEmoticonQueryWrapper = new QueryWrapper<>();
        usersEmoticonQueryWrapper.eq("user_id", uid);
        UsersEmoticon usersEmoticon = usersEmoticonMapper.selectOne(usersEmoticonQueryWrapper);
        String emoticonIds = usersEmoticon.getEmoticonIds();
        String[] ids = emoticonIds.split(",");
        List<String> eids = Arrays.asList(ids);

        systemEmoticonListDTOS=emoticons.stream().map(item->{
            SystemEmoticonListDTO systemEmoticonListDTO = new SystemEmoticonListDTO();
            systemEmoticonListDTO.setId(item.getId());
            systemEmoticonListDTO.setIcon(item.getIcon());
            systemEmoticonListDTO.setName(item.getName());

            //0该用户未添加 1用户已添加
            if (eids.contains(item.getId().toString())){
                systemEmoticonListDTO.setStatus(1);
            }else {
                systemEmoticonListDTO.setStatus(0);
            }


            return systemEmoticonListDTO;
        }).collect(Collectors.toList());
        return Result.success(systemEmoticonListDTOS);
    }

    /**
     * 添加系统表情包
     * @param uid
     * @param emoticon_id
     * @return
     */
    @Override
    public Result systemInstall(Integer uid,Integer type, Integer emoticon_id) {
        QueryWrapper<UsersEmoticon> usersEmoticonQueryWrapper = new QueryWrapper<>();
        usersEmoticonQueryWrapper.eq("user_id", uid);
        UsersEmoticon usersEmoticon = usersEmoticonMapper.selectOne(usersEmoticonQueryWrapper);
        if (type==1){//添加系统表情包
            if (usersEmoticon!=null){
                String emoticonIds = usersEmoticon.getEmoticonIds();
                String[] ids = emoticonIds.split(",");
                List<String> eids = Arrays.asList(ids);
                if (eids.contains(emoticon_id.toString())){
                    return Result.fail("您已添加过该表情包哦！");
                }
                if (emoticonIds.isEmpty()){
                    emoticonIds = emoticon_id.toString();
                }else {
                    emoticonIds = emoticonIds + "," + emoticon_id;
                }

                usersEmoticon.setEmoticonIds(emoticonIds);

                usersEmoticonMapper.updateById(usersEmoticon);
            }else {//用户未添加任何系统表情包
                UsersEmoticon usersEmoticon1 = new UsersEmoticon();
                usersEmoticon1.setEmoticonIds(emoticon_id.toString());
                usersEmoticon1.setUserId(uid);
                usersEmoticonMapper.insert(usersEmoticon1);
            }
            Emoticon emoticon = emoticonMapper.selectById(emoticon_id);
            SysEmoticonVO sysEmoticonVO = new SysEmoticonVO();
            sysEmoticonVO.setName(emoticon.getName());
            sysEmoticonVO.setUrl(emoticon.getIcon());
            sysEmoticonVO.setEmoticon_id(emoticon_id);

            QueryWrapper<EmoticonItem> emoticonItemQueryWrapper = new QueryWrapper<>();
            emoticonItemQueryWrapper.eq("emoticon_id",emoticon_id).orderByDesc("updated_at");
            List<EmoticonItem> emoticonItems = emoticonItemMapper.selectList(emoticonItemQueryWrapper);
            List<CollectEmoticonVO> collectEmoticonVOS = new ArrayList<>();
            collectEmoticonVOS=emoticonItems.stream().map(item->{
                CollectEmoticonVO collectEmoticonVO = new CollectEmoticonVO();
                collectEmoticonVO.setSrc(item.getUrl());
                collectEmoticonVO.setMedia_id(item.getId());
                return collectEmoticonVO;
            }).collect(Collectors.toList());

            sysEmoticonVO.setList(collectEmoticonVOS);
            return Result.success(sysEmoticonVO);
        }else {//移除已添加的系统表情包
            String[] emoticonIds = usersEmoticon.getEmoticonIds().split(",");
            List<String> eids = new ArrayList<String>(Arrays.asList(emoticonIds));
            String s = emoticon_id.toString();
            boolean remove = eids.remove(s);
            if (remove){
                String ids = StringUtils.join(eids, ",");
                usersEmoticon.setEmoticonIds(ids);
                usersEmoticonMapper.updateById(usersEmoticon);
                return Result.success();
            }
            return Result.fail();
        }
    }
}
